<?php
/**
 * OAuthController class file.
 *
 * @author Zhang Jinlong <466028373@qq.com>
 * @link http://www.ijianzhi.cn
 * @copyright Copyright &copy; 2013 DianJin Soft
 */

class OAuthController extends Controller
{
    /**
     * QQ登录
     */
    public function actionLoginForQQ()
    {
        $handle = new OAuthHandlerForQQ();
        $handle->login();
    }

    /**
     * QQ登录回调地址
     */
    public function actionCallbackForQQ()
    {
        /* 执行QQ CONNECT API */
        try
        {
            $handle = new OAuthHandlerForQQ();
            $accessToken = $handle->callback();
            $openId = $handle->getOpenId();

            $api = new OAuthApiForQQ();
            $response = $api->getUserInfo();
        }
        catch (Exception $e)
        {
            Yii::log(Helper::generateLogMessage($e), CLogger::LEVEL_ERROR);

            Helper::showMessage(Yii::t('app', 'Connect to the qq fail.')
                , Yii::app()->urlManager->createUrl('site/login'), 3, Constants::OPERATION_FAILED);
        }

        /* 同步用户数据，执行站点登录 */
        $user = new User();

        $userData = array(
            'nickname' => $response['nickname'],
            'gender' => $response['gender'],
            'figureurl_2' => $response['figureurl_2'],
        );

        if ($user->loginForQQ($openId, $accessToken, $userData) === FALSE)
        {
            Helper::showMessage(Yii::t('app', 'Login fail.')
                , Yii::app()->urlManager->createUrl('site/login'), 3, Constants::OPERATION_FAILED);
        }

        Helper::showMessage(NULL, Yii::app()->urlManager->createUrl('user/index'), 0);
    }
}
